package com.smcad.gsm.view;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.google.android.maps.MapView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.smcad.gsm.Main;
import com.smcad.gsm.R;
import com.smcad.gsm.WebService;

public class LocationViewers extends LinearLayout {

	private final static int MAX_MAPPED_LISTINGS = 15;
	private MapLocationOverlay overlay;
	static GetGarageSaleListingTask task;
	
    //  Known lat/long coordinates that we'll be using.
    private List<MapLocation> mapLocations;
    
    public static MapView mapView;
    
	public LocationViewers(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}

	public LocationViewers(Context context) {
		super(context);
		init();
	}
	
	public void init() {		

		setOrientation(VERTICAL);
		setLayoutParams(new LinearLayout.LayoutParams(android.view.ViewGroup.LayoutParams.FILL_PARENT,android.view.ViewGroup.LayoutParams.FILL_PARENT));
		String api = getResources().getString(R.string.GOOGLE_MAPS_API_KEY);
		mapView = new MapView(getContext(),api);
		mapView.setEnabled(true);
		mapView.setClickable(true);
		addView(mapView);
		overlay = new MapLocationOverlay(this);
		mapView.getOverlays().add(overlay);
    	mapView.getController().setZoom(10);
    	getMapLocations();
    	
	}
	
	
	public List<MapLocation> getMapLocations() {
//		task = new GetGarageSaleListingTask();
//		task.applicationContext = Main.getContext();
//		task.execute();
		updateListings();
		
//		mapLocations = new ArrayList<MapLocation>();
//		mapLocations.add(new MapLocation("Avinashi road", "Avinashi road, Coimbatore", "Coimbatore"));
//		mapLocations.add(new MapLocation("Marina Beach", "Marina Beach, Chennai", "Marina"));
//		mapLocations.add(new MapLocation("Taj Mahal", "Taj Mahal, New Delhi", "Delhi"));
//		mapLocations.add(new MapLocation("Meenakshi Temple", "Meenakshi Temple, Madurai", "Madurai"));
		return mapLocations;
	}
	
	private void updateListings() {
		if (mapLocations == null) {
			mapLocations = new ArrayList<MapLocation>();

			// Instantiate the Web Service Class with he URL of the web service
			// that you must pass
			WebService webService = new WebService(
					"http://mcad.no-ip.org:8080/GarageSaleFinder/garageSale/getListingsAsJson");

			// Pass the parameters if needed , if not then pass dummy one as
			// follows
			Map<String, String> p = new HashMap<String, String>();

			try {
				p.put("zip", URLEncoder.encode("55311", "UTF-8"));
			} catch (UnsupportedEncodingException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}

			// Get JSON response from server the "" are where the method name
			// would
			// normally go if needed example
			String response = webService.webGet("", p);

			try {
				// Parse Response into our object
				Type collectionType = new TypeToken<ArrayList<MapLocation>>() {
				}.getType();

				// JSON expects an list so can't use our ArrayList from the
				// lstart
				List<MapLocation> lst = new Gson().fromJson(response,
						collectionType);
				System.out.println("list = " + lst);

				// Now that we have that list lets add it to the ArrayList which
				// will hold our items.
				for (MapLocation l : lst) {
					if (mapLocations.size() > MAX_MAPPED_LISTINGS)
						break;
					MapLocation ml = new MapLocation(l.title, l.address,
							l.description);
					mapLocations.add(ml);
//					System.out.println(ml);
				}
				if (mapLocations.size() == 0) {
					Toast.makeText(Main.getContext(), "No Results Found",
							Toast.LENGTH_LONG).show();
				}
			} catch (Exception e) {
				Log.d("Error: ", e.getMessage());
			}
			if ((mapLocations.size() > 0) && (mapLocations.get(0).getPoint() != null)) {
				mapView.getController().setCenter(mapLocations.get(0).getPoint());
			}
		}
	}

	public MapView getMapView() {
		return mapView;
	}
	
	private class GetGarageSaleListingTask extends AsyncTask<Void, Void, String> {
		private ProgressDialog dialog;
		protected Context applicationContext;

		@Override
		protected void onPreExecute() {
			this.dialog = ProgressDialog.show(applicationContext,
					"Please wait...contacting the tubes.",
					"Requesting Garage Sale List", true);
		}

		@Override
		protected String doInBackground(Void... params) {
			if (mapLocations == null) {
				mapLocations = new ArrayList<MapLocation>();

				// Instantiate the Web Service Class with he URL of the web service
				// that you must pass
				WebService webService = new WebService(
						"http://mcad.no-ip.org:8080/GarageSaleFinder/garageSale/getListingsAsJson");

				// Pass the parameters if needed , if not then pass dummy one as
				// follows
				Map<String, String> p = new HashMap<String, String>();

				try {
					p.put("zip", URLEncoder.encode("55325", "UTF-8"));
				} catch (UnsupportedEncodingException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}

				// Get JSON response from server the "" are where the method name
				// would
				// normally go if needed example
				String response = webService.webGet("", p);

				try {
					// Parse Response into our object
					Type collectionType = new TypeToken<ArrayList<MapLocation>>() {
					}.getType();

					// JSON expects an list so can't use our ArrayList from the
					// lstart
					List<MapLocation> lst = new Gson().fromJson(response,
							collectionType);
					System.out.println("list = " + lst);

					// Now that we have that list lets add it to the ArrayList which
					// will hold our items.
					for (MapLocation l : lst) {
						MapLocation ml = new MapLocation(l.title, l.address,
								l.description);
						mapLocations.add(ml);
						System.out.println(ml);
					}
					if (mapLocations.size() == 0) {
						Toast.makeText(Main.getContext(), "No Results Found",
								Toast.LENGTH_LONG).show();
					}
				} catch (Exception e) {
					Log.d("Error: ", e.getMessage());
				}
			}
			return "";
		}

		@Override
		protected void onPostExecute(String s) {
			this.dialog.cancel();
//			if ((mapLocations.size() > 0) && (mapLocations.get(0).getPoint() != null)) {
//				mapView.getController().setCenter(mapLocations.get(0).getPoint());
//			}
//			// refresh screen
//			mapView.invalidate();
		}
	}
	
}
